/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.business;

import entities.Account;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author HoangHai
 */
@Stateless
@LocalBean
public class accountBean {

    @PersistenceContext(unitName = "DeclarationBoard-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public Account login(String user, String pass) {
        Query query = em.createNamedQuery("Account.loginAcc").setParameter("accName", user).setParameter("accPass", pass);
        Account acc = (Account) query.getSingleResult();
        return acc;
    }

    public List<Account> allAccount() {
        List<Account> accounts = em.createNamedQuery("Account.findAll").getResultList();
        return accounts;
    }

    public Account findAccByID(int id) {
        Account account = (Account) em.createNamedQuery("Account.findByAccID").setParameter("accID", id).getSingleResult();
        return account;
    }

    public Account findAccByName(String name) {
        Account account = (Account) em.createNamedQuery("Account.findByAccName").setParameter("accName", name).getSingleResult();
        return account;
    }

    public boolean addAccount(Account a) {
        boolean flag;

        try {

            em.persist(a);
            flag = true;

        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public boolean updateAccount(Account a) {
        boolean flag;
        try {
            em.merge(a);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public boolean delAccount(int id) {
        boolean flag;
        try {
            Account a = findAccByID(id);
            em.remove(a);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
}
